package com.qyi.activemq.queue.consumer;

import com.qyi.activemq.queue.ActiveMQProperties;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.messaginghub.pooled.jms.JmsPoolConnectionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jms.JmsPoolConnectionFactoryFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;

import javax.jms.ConnectionFactory;


/**
 * @author luqi
 * @Date 2021/3/11 10:04
 * @Description TODO
 */
@Configuration
@EnableJms
public class MqConsumerConfig {

    public ActiveMQConnectionFactory activeMQConnectionFactory(ActiveMQProperties properties) {
        ActiveMQConnectionFactory activeMQConnectionFactory =
                new ActiveMQConnectionFactory(
                        properties.getUser(),
                        properties.getPassword(),
                        properties.getBrokerUrl());
        return activeMQConnectionFactory;
    }

    @Bean(name = "consumerConnection")
    JmsPoolConnectionFactory jmsConnectionFactory(ActiveMQProperties properties) {
        ActiveMQConnectionFactory connectionFactory = (activeMQConnectionFactory(properties));
        JmsPoolConnectionFactory pooledConnectionFactory = (new JmsPoolConnectionFactoryFactory(properties.getPool())).createPooledConnectionFactory(connectionFactory);
        return pooledConnectionFactory;
    }

    @Bean
    public JmsListenerContainerFactory<?> jmsListenerContainerQueue(@Qualifier("consumerConnection") ConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
        bean.setConnectionFactory(connectionFactory);
        return bean;
    }
}
